/**
 * 任务服务
 */

const BaseProjectService = require('./base_project_service.js');
// 使用统一配置入口引用模型
const { TaskModel } = require('../config/models_config.js');
const timeUtil = require('../../../framework/helpers/time_util.js');
const dbUtil = require('../../../framework/database/db_util.js');
const util = require('../../../framework/helpers/util.js');

class TaskService extends BaseProjectService {

    /**
     * 获取任务列表
     * @param {Object} param 查询参数
     */
    async getTaskList({
        search,
        projectId,
        assigneeId,
        type,
        status,
        priority,
        sortType,
        sortVal,
        orderBy,
        page,
        size,
        isTotal = true,
        oldTotal
    }) {
        // 构建查询条件
        let where = {};
        
        if (projectId) where.TASK_PROJECT_ID = projectId;
        if (assigneeId) where.TASK_ASSIGNEE_ID = assigneeId;
        if (type) where.TASK_TYPE = type;
        if (status) where.TASK_STATUS = status;
        if (priority) where.TASK_PRIORITY = priority;
        
        if (search) {
            where.TASK_TITLE = {
                $regex: search,
                $options: 'i'
            };
        }
        
        // 构建排序
        let sort = {
            TASK_ADD_TIME: -1
        };
        
        if (sortType && sortVal) {
            sort = {
                [sortType]: sortVal
            };
        }
        
        if (orderBy) {
            sort = orderBy;
        }
        
        // 获取总数
        let total = 0;
        if (isTotal) {
            total = await dbUtil.count(TaskModel.CL, where);
        }
        
        // 查询数据
        let list = await dbUtil.getAll(TaskModel.CL, where, {
            sort,
            skip: (page - 1) * size,
            limit: size
        });
        
        return {
            list,
            total: isTotal ? total : oldTotal
        };
    }
    
    /**
     * 获取任务统计数据
     * @param {String} projectId 项目ID
     */
    async getTaskStats(projectId) {
        if (!projectId) return null;
        
        // 查询项目所有任务
        let tasks = await dbUtil.getAll(TaskModel.CL, {
            TASK_PROJECT_ID: projectId
        });
        
        if (!tasks || tasks.length === 0) {
            return {
                total: 0,
                completed: 0,
                inProgress: 0,
                notStarted: 0,
                completionRate: 0
            };
        }
        
        // 统计数据
        let total = tasks.length;
        let completed = 0;
        let inProgress = 0;
        let notStarted = 0;
        
        for (let task of tasks) {
            if (task.TASK_STATUS === TaskModel.STATUS.COMPLETED) {
                completed++;
            } else if (task.TASK_STATUS === TaskModel.STATUS.IN_PROGRESS) {
                inProgress++;
            } else if (task.TASK_STATUS === TaskModel.STATUS.NOT_STARTED) {
                notStarted++;
            }
        }
        
        // 计算完成率
        let completionRate = Math.round((completed / total) * 100);
        
        return {
            total,
            completed,
            inProgress,
            notStarted,
            completionRate
        };
    }
    
    /**
     * 获取任务类型分布统计
     * @param {String} projectId 项目ID
     */
    async getTaskTypeDistribution(projectId) {
        if (!projectId) return null;
        
        // 查询项目所有任务
        let tasks = await dbUtil.getAll(TaskModel.CL, {
            TASK_PROJECT_ID: projectId
        });
        
        if (!tasks || tasks.length === 0) {
            return [];
        }
        
        // 统计不同类型的任务数量
        let typeCountMap = {};
        
        for (let task of tasks) {
            let type = task.TASK_TYPE;
            if (!typeCountMap[type]) {
                typeCountMap[type] = 0;
            }
            typeCountMap[type]++;
        }
        
        // 构建结果数组
        let result = [];
        
        for (let type in typeCountMap) {
            let typeName = '';
            
            // 获取类型名称
            for (let key in TaskModel.TYPE) {
                if (TaskModel.TYPE[key] == type) {
                    typeName = TaskModel.TYPE_DESC[key];
                    break;
                }
            }
            
            result.push({
                type: parseInt(type),
                typeName,
                count: typeCountMap[type]
            });
        }
        
        return result;
    }
    
    /**
     * 获取任务优先级分布统计
     * @param {String} projectId 项目ID
     */
    async getTaskPriorityDistribution(projectId) {
        if (!projectId) return null;
        
        // 查询项目所有任务
        let tasks = await dbUtil.getAll(TaskModel.CL, {
            TASK_PROJECT_ID: projectId
        });
        
        if (!tasks || tasks.length === 0) {
            return [];
        }
        
        // 统计不同优先级的任务数量
        let priorityCountMap = {};
        
        for (let task of tasks) {
            let priority = task.TASK_PRIORITY;
            if (!priorityCountMap[priority]) {
                priorityCountMap[priority] = 0;
            }
            priorityCountMap[priority]++;
        }
        
        // 构建结果数组
        let result = [];
        
        for (let priority in priorityCountMap) {
            let priorityName = '';
            
            // 获取优先级名称
            for (let key in TaskModel.PRIORITY) {
                if (TaskModel.PRIORITY[key] == priority) {
                    priorityName = TaskModel.PRIORITY_DESC[key];
                    break;
                }
            }
            
            result.push({
                priority: parseInt(priority),
                priorityName,
                count: priorityCountMap[priority]
            });
        }
        
        return result;
    }
}

module.exports = TaskService; 